package org.jili.novoland.listener;

import org.jili.novoland.base.LayerManager;
import org.jili.novoland.game.ResourceManager;
import org.jili.novoland.game.Role;

import android.content.Context;
import android.view.MotionEvent;
import android.view.View;

public class BattleListener implements IControlListener {
    LayerManager layerManager;
    IControlListener nextControlListener = this;
    
    private int lastX, lastY;
    private boolean roleSelected = false;
    private boolean action = false;
    private Role currentRole = null;

    public BattleListener(Context ctx) {
        super();
        layerManager = new LayerManager();
        ResourceManager.getInstance(ctx).loadBattle(layerManager);

    }

    public boolean onTouch(View v, MotionEvent event) {
        if (action)
            return true;
        int dx, dy;
        int x = (int) event.getRawX();
        int y = (int) event.getRawY();
        switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            lastX = x;
            lastY = y;
            break;
        case MotionEvent.ACTION_MOVE:
            dx = x - lastX;
            dy = y - lastY;
            lastX = x;
            lastY = y;

            layerManager.drag(dx, dy);
            // resourceManager.getLayerManager().paint(resourceManager., x, y)
            // Log.d(DragListener.class.toString(),"deltaX:" +
            // Integer.toString(deltaX) + ", deltaY:" +
            // Integer.toString(deltaY));

            break;
        case MotionEvent.ACTION_UP:
            Role role = layerManager.getCharaterByXY(x, y);
            if (role != null) {
                layerManager.getBattleFieldMap().setMoveMatrix(role);
                currentRole = role;
                roleSelected = true;
//                layerManager.getMenu().setType(Menu.TYPE_ROLE_SELECTED);
//                layerManager.getMenu().show(role);
            } else {
                if (roleSelected) {
                    if (layerManager.getBattleFieldMap().setMoveList(layerManager.getColByX(x),
                            layerManager.getRowByY(y), currentRole)) {
                        currentRole.move();
//                        layerManager.getBattleFieldMap().setMoveMatrix(currentRole);

                    } else {
                        roleSelected = false;
                        layerManager.getBattleFieldMap().clearMoveMatrix();
                        currentRole = null;
                    }
                }
            }
            break;
        default:
            break;
        }

        return true;
    }

    @Override
    public LayerManager getLayerManager() {
        return layerManager;
    }

    @Override
    public IControlListener getNextControlListener() {
        return nextControlListener;
    }

}
